<?php

/**
 * Created by PhpStorm
 * User Niu Yong Qiang
 * Date 2021/9/17 19:59
 */

namespace App\Models;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\HasMany;

class SysUserRoleModel extends BaseModel
{
    protected $table='info_sys_user_has_roles';
    public $timestamps = false;

    /**
     * 删除
     * @param $where
     * @return mixed
     */
    public function deleteUserRole($where){
        if(empty($where))
            return false;
        return self::query()->where($where)->delete();
    }


    /**
     * 新增
     * @param $data
     * @return bool|null
     */
    public function insertUserRole($data):? bool
    {
        if(empty($data))
            return false;
        return self::query()->insert($data);
    }

    /**
     * 获取list数据
     * @param $where
     * @return Builder[]|Collection
     */
    public function userRoleAll($where){
        $list = self::query()
            ->leftJoin('info_sys_roles', 'info_sys_roles.id', '=', 'info_sys_user_has_roles.role_id')
            ->selectRaw('info_sys_user_has_roles.role_id')
            ->where($where)
            ->get();

        return $list ? $list->toArray() : [];

    }

    /**
     * @param array $where
     * @param string $field
     * @param array $id
     * @return array|null
     */
    public static function getDataOne(array $where=[], string $field='', array $id=[]):?array
    {
        $res = self::query()
            ->where($where);

        if (!empty($id)){
            $res->whereIn($field, $id);
        }

        return $res->get()->toArray();
    }

    /**
     * @param array $where
     * @param string $field
     * @param array $id
     * @return array|null
     */
    public static function getSing(array $where=[], string $field='', array $id=[]):?array
    {
        $res = self::query()
            ->where($where)
            ->with('role');

        if (!empty($id)){
            $res->whereIn($field, $id);
        }

        $res = $res->first();
        return !empty($res) ? $res->toArray() :[];
    }

    public function role(): HasMany
    {
        return $this->hasMany(SysRoleModel::class, 'id', 'role_id');
    }

}
